import {
  getUrlQuery,
  urlExcept
} from './utils/utils';
import {
  casConfig
} from './config';
import qs from 'qs';
import url from 'url';
import {
  getParams
} from './params';
export default function() {
  let url = window.location.href;
  let redirect = getUrlQuery(url, 'redirect');
  if (redirect == undefined) {
    redirect = url;
    if (isExclude()) {
      redirect = window.location.origin + casConfig.get('redirect', '/');
    } else {
      redirect = url;
    }
  }
  return encodeURIComponent(buildRedirect(redirect));
}
export function isExclude() {
  let exclude = casConfig.get('exclude', []);
  let re = false;
  if (exclude.length > 0) {
    exclude.forEach(v => {
      if (window.location.href.indexOf(v) !== -1) {
        re = true;
      }
    })
  }
  return re;
}

function buildRedirect(redirect) {
  let urlObj = url.parse(redirect, true);
  let urlQuery = urlObj.query;
  delete urlObj.query;
  delete urlObj.search;
  if (urlQuery.ticket) {
    delete urlQuery.ticket;
  }
  let params = getParams();
  urlObj.query = { ...urlQuery,
    ...params
  }
  return url.format(urlObj);
}